package com.caidan.diagram.common;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @GetMapping
    public void createCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //获取验证码文本
        String code = lineCaptcha.getCode();
        log.info("验证码：{}", code);
        // 存入 session
        request.getSession().setAttribute("code", code);
        //
        lineCaptcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();
    }

}
